#!/usr/bin/env python

"""
Pybanet !

Send bouncing balls through the network ;)

"""

# System imports
import os, sys, time, ConfigParser, traceback
# Our imports
from network import NetListener, net_send
from ball import BallArea, pump_events, demo_balls

port = 42042
demo = True
    
# Try to open config file given on the command line or config.ini
if len(sys.argv) > 1:
    config_file = sys.argv[1]
else:
    config_file = "config.ini"

conf = ConfigParser.ConfigParser()
try:
    conf.readfp(open(config_file))
except IOError:
    print "Config file not found: %s" % (config_file)
    sys.exit()

# Parsing the config file
try:

    l_wall = conf.getboolean("left", "wall")
    if not l_wall: l_addr = (conf.get("left","address"), port)

    r_wall = conf.getboolean("right", "wall")
    if not r_wall: r_addr = (conf.get("right","address"), port)

    if conf.has_section("ball"):
        my_ball = conf.get("ball","file")
        if os.access(my_ball,os.F_OK):
            demo = False

except (ConfigParser.ParsingError, ConfigParser.NoSectionError, ConfigParser.NoOptionError), e:
    print "Config file error: %s" % (e)
    sys.exit()

# ======= OK ! Let's begin ! ============

# start playing field in a new thread
ba = BallArea(640,480,l_wall,r_wall)
ba.start()

if demo:
    demo_balls(ba)
else:
    ba.perso_img = my_ball
    ba.inject_rnd(my_ball)

# start network thread
netl = NetListener(port)
netl.start()

# That's the main loop, running as long as the
# playing field thread exists
try:
    while ba.isAlive():

        # look if there's a packet for us
        packet = netl.get_data()
        if packet:
            try:
                (f,x,y,dx,dy) = packet.split(":")
                ba.inject(f,int(x),int(y),int(dx),int(dy))
            except ValueError, e:
                print "Bad packet: %s" % (e)
                pass

        # look if there's a ball waiting for departure
        eball = ba.get_ejected()
        if eball:
            if eball.x > 0:
                net_send(eball, r_addr)
            else:
                net_send(eball, l_addr)

        # forward unhandled events, then wait a little
        pump_events()
        time.sleep(.1)

# boring but useful stuff 
except KeyboardInterrupt:
    print "KeyboardInterrupt !"
except Exception, e:
    traceback.print_exc()
finally:
    print "Stopping threads, please wait ..."
    netl.stop()
    ba.stop()
    netl.join(1)
    ba.join(2)
    print "Kthxbye !"
    sys.exit(0)
